package com.example.kkblog.service;

import com.example.kkblog.config.exception.KKBlogException;
import com.example.kkblog.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

@Service
public class EmailService {
    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender mailSender; // JavaMailSender是Spring Email的核心组件，负责发送邮件

    @Value("${spring.mail.username}")
    private String from;

    @Value("${kkBlog.protocol}")
    private String protocol;

    @Value("${kkBlog.ip-address}")
    private String host;

    @Value("${server.port}")
    private String server_port;

    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage(); // MimeMessage用于封装邮件的相关信息
            MimeMessageHelper helper = new MimeMessageHelper(message); // MimeMessageHelper用于辅助构建MimeMessage对象
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); // 不写true默认text格式发送邮件
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败："+ e.getMessage());
        }
    }

    public boolean sendActivateHtml(String to, String code) throws Exception {
        try {
            MimeMessage message = mailSender.createMimeMessage(); // MimeMessage用于封装邮件的相关信息
            MimeMessageHelper helper = new MimeMessageHelper(message); // MimeMessageHelper用于辅助构建MimeMessage对象
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("KKBlog用户注册验证码");
            helper.setText(getActivateHtmlContent(to, code), true); // 不写true默认text格式发送邮件
            mailSender.send(helper.getMimeMessage());
        } catch (Exception e) {
            logger.error("发送邮件失败："+ e.getMessage());
            throw new Exception(e.getMessage());
        }
        return true;
    }

    public boolean sendResetPasswordHtml(String to, String code){
        try {
            MimeMessage message = mailSender.createMimeMessage(); // MimeMessage用于封装邮件的相关信息
            MimeMessageHelper helper = new MimeMessageHelper(message); // MimeMessageHelper用于辅助构建MimeMessage对象
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("小白书————密码重置");
            helper.setText(getResetHtmlContent(to, code), true); // 不写true默认text格式发送邮件
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败："+ e.getMessage());
            throw new KKBlogException(e.getMessage());
        }
        return true;
    }
    public String getActivateHtmlContent(String to, String code) throws Exception {
        String hmtl = "<!DOCTYPE html>" +
                "<html lang=\"en\" xmlns:th=\"http://www.thymeleaf.org\">" +
                "<head>" +
                "    <meta charset=\"UTF-8\">" +
                "    <title>KKBlog注册验证码</title>" +
                "</head>" +
                "<body>" +
                "<div style=\"background-color:#ECECEC; padding: 15px;\">" +
                "    <table cellpadding=\"0\" align=\"center\"" +
                "           style=\"width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;\">" +
                "        <tbody>" +
                "        <tr>" +
                "            <th valign=\"middle\"" +
                "                style=\"height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #16b9a9; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;\">" +
                "                <font face=\"微软雅黑\" size=\"5\" style=\"color: rgb(255, 255, 255); \">KKBlog注册验证码</font>" +
                "            </th>" +
                "        </tr>" +
                "        <tr>" +
                "            <td>" +
                "                <div style=\"padding:25px 35px 40px; background-color:#fff;\">" +
                "                    <h2 style=\"margin: 5px 0px; \">" +
                "                        <font color=\"#333333\" style=\"line-height: 20px; \">" +
                "                            <font style=\"line-height: 22px; \" size=\"4\">" +
                "                                亲爱的<b>" + to + "</b>，您好：</font>" +
                "                        </font>" +
                "                    </h2>" +
                "                    <p>首先感谢您使用KKBlog，您的验证码是:<br><br>" +
                "                        <a style=\"font-size: 24px;font-weight: bold;text-decoration: underline\" >" + code + "</a><br><br>" +
                "                        验证驸5分钟内有效，为了保障您的账户安全，请勿向任何人提供此验证码。感谢您的支持!<br>" +
                "                        如果您有什么疑问可以联系管理员，Email: 2250671362@qq.com</p>" +
                "                    <p align=\"right\">KKBlog</p>" +
                "                    <p align=\"right\">" + DateUtils.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss") + "</p>" +
                "                    <div style=\"width:700px;margin:0 auto;\">" +
                "                        <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">" +
                "                            <p>本邮件系统自动发送，请勿回复!<br>" +
                "                                请保管好您的邮箱，避免账号被他人盗用" +
                "                            </p>" +
                "                            <p>© 2024 Powered by Derek</p>" +
                "                        </div>" +
                "                    </div>" +
                "                </div>" +
                "            </td>" +
                "        </tr>" +
                "        </tbody>" +
                "    </table>" +
                "</div>" +
                "</body>" +
                "</html>";
        return hmtl;
//        Context context = new Context();
//        context.setVariable("codeType", "KKBlog验证码");
//        context.setVariable("email", to);
//        context.setVariable("title", "KKBlog注册验证码");
//        context.setVariable("code", code);
//        context.setVariable("date", DateUtils.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));
//        try {
//            return templateEngine.process(System.getProperty("user.dir") + "/src/main/resources/templates/email/RegisterTemplate.html", context);
//        } catch (Exception e) {
//            throw new Exception("邮件模板查询失败！");
//        }
    }

    public String getResetHtmlContent(String to, String code){
        Context context = new Context();
        context.setVariable("title", "密码重置");
        context.setVariable("email", to);
        context.setVariable("code", code);
        context.setVariable("date", DateUtils.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));
        context.setVariable("action", String.format("%s://%s:%s/%s", protocol, host, server_port, "reset-password"));
        return templateEngine.process("/email/ResetPasswordTemplate.html", context);
    }
}
